package com.lixin.juc.async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class MainApplication {

    public static void main(String[] args) {
        //testAsyncVoid();
        testAsyncResult();
    }

    // 异步回调有返回值
    public static void testAsyncResult() {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "有返回值异常任务执行";
        });

        System.out.println("这里开始执行");
        try {
            String result = future.whenComplete((t, u) -> {
                System.out.println("t:" + t);
                System.out.println("u:" + u);
            }).exceptionally(Throwable::getMessage).get();
            System.out.println("结果：" + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    // 异步回调无返回值
    public static void testAsyncVoid() {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("无返回值异步任务执行");
        });
        try {
            future.get(); // 阻塞并获取返回结果，不调用get方法，异步任务一样会执行
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("这里开始执行");
    }

}
